package com.example.test.dialogfactory;

import android.Manifest.permission;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import easier.amap.AMapEasier;
import easier.app.x.result.Permission;
import easier.app.x.result.starter.StartForResult;
import easier.app.x.starter.IntentBuilder;
import easier.app.x.task.ScheduledTask;
import easier.window.dialog.impl.CancelConfirmDialogFragment;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public class MainActivity59 extends AppCompatActivity {

    private static final String TAG = "MainActivity59";

    private final ScheduledTask mScheduledTask = new ScheduledTask();

    public static void start( Context context ) {

        Intent starter = new Intent( context, MainActivity59.class );
        context.startActivity( starter );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main59 );
        initView();
    }

    private void initView() {

        Button click = (Button) findViewById( R.id.click );
        click.setOnClickListener( new OnClickListener() {

            private Dialog mDialog;

            @Override
            public void onClick( View v ) {

                if ( mDialog == null ) {
                    mDialog = new Dialog();
                    mDialog.setRunnable( new Runnable() {
                        @Override
                        public void run() {

                        }
                    } );
                    mDialog.setDismiss( new Runnable() {
                        @Override
                        public void run() {

                            mDialog = null;
                        }
                    } );
                }

                if ( mDialog.isShowing() ) {
                    mDialog.dismiss();
                }

                mDialog.show( getSupportFragmentManager(), "private" );
                AMapEasier.notifyUpdatePrivacyShow( v.getContext() );
            }
        } );

        Button location = (Button) findViewById( R.id.location );
        location.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick( View v ) {

                createCheckLocationPermissionWithRequest( v.getContext() )
                    .subscribe( new Observer< Boolean >() {
                        @Override
                        public void onSubscribe( @NonNull Disposable d ) {

                        }

                        @Override
                        public void onNext( @NonNull Boolean aBoolean ) {

                            Log.i( TAG, "onNext: " + aBoolean );
                            if ( aBoolean ) {
                                AMapEasier aMapEasier = create();
                                aMapEasier.startLocation( new AMapLocationListener() {
                                    @Override
                                    public void onLocationChanged( AMapLocation aMapLocation ) {

                                        Log.i( TAG, "onLocationChanged: " + AMapEasier.print( aMapLocation ) );
                                        aMapEasier.destroyLocation();
                                    }
                                } );
                            }
                        }

                        @Override
                        public void onError( @NonNull Throwable e ) {

                            e.printStackTrace();
                        }

                        @Override
                        public void onComplete() {

                        }
                    } );
            }
        } );

        findViewById( R.id.location2 ).setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View v ) {

                createCheckLocationPermission( v.getContext() )
                    .subscribe( new Observer< Boolean >() {
                        @Override
                        public void onSubscribe( @NonNull Disposable d ) {

                        }

                        @Override
                        public void onNext( @NonNull Boolean aBoolean ) {

                            Log.i( TAG, "onNext:2 " + aBoolean );
                            if ( aBoolean ) {
                                AMapEasier aMapEasier = create();
                                aMapEasier.startLocation( new AMapLocationListener() {
                                    @Override
                                    public void onLocationChanged( AMapLocation aMapLocation ) {

                                        Log.i( TAG, "onLocationChanged: " + AMapEasier.print( aMapLocation ) );
                                        aMapEasier.destroyLocation();
                                    }
                                } );
                            }
                        }

                        @Override
                        public void onError( @NonNull Throwable e ) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    } );
            }
        } );

        findViewById( R.id.location3 ).setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View v ) {

                mScheduledTask.stop();
                mScheduledTask.startImmediately( new Runnable() {
                    @Override
                    public void run() {

                        findViewById( R.id.location2 ).performClick();
                    }
                }, 30 * 1000 );
            }
        } );
    }

    private AMapEasier create() {

        return new AMapEasier( getApplicationContext() );
    }

    private Observable< Boolean > createCheckLocationPermission( Context context ) {

        return Observable.create( new ObservableOnSubscribe< Boolean >() {
            @Override
            public void subscribe( @NonNull ObservableEmitter< Boolean > emitter ) throws Throwable {

                boolean coarse = Permission.check( context, permission.ACCESS_COARSE_LOCATION );
                boolean fine = Permission.check( context, permission.ACCESS_FINE_LOCATION );

                if ( coarse || fine ) {
                    emitter.onNext( true );
                    emitter.onComplete();
                } else {
                    emitter.onNext( false );
                    emitter.onComplete();
                }
            }
        } );
    }

    private Observable< Boolean > createCheckLocationPermissionWithRequest( Context context ) {

        boolean coarse = Permission.check( context, permission.ACCESS_COARSE_LOCATION );
        boolean fine = Permission.check( context, permission.ACCESS_FINE_LOCATION );

        if ( coarse || fine ) {
            return Observable.just( true );
        }
        return Observable.create( new ObservableOnSubscribe< Boolean >() {
            @Override
            public void subscribe( @NonNull ObservableEmitter< Boolean > emitter ) throws Throwable {

                new AlertDialog.Builder( context )
                    .setTitle( "提示" )
                    .setMessage( "请打开定位权限" )
                    .setPositiveButton(
                        "确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick( DialogInterface dialog, int which ) {

                                StartForResult.registerForActivityResult( getSupportFragmentManager(),
                                    IntentBuilder.appSettingIntent( context ),
                                    new ActivityResultCallback< ActivityResult >() {
                                        @Override
                                        public void onActivityResult( ActivityResult result ) {

                                            boolean coarse = Permission.check( context, permission.ACCESS_COARSE_LOCATION );
                                            boolean fine = Permission.check( context, permission.ACCESS_FINE_LOCATION );

                                            emitter.onNext( coarse || fine );
                                            emitter.onComplete();
                                        }
                                    } );
                            }
                        } )
                    .setNegativeButton( "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick( DialogInterface dialog, int which ) {

                            emitter.onNext( false );
                            emitter.onComplete();
                        }
                    } )
                    .setOnDismissListener( new OnDismissListener() {
                        @Override
                        public void onDismiss( DialogInterface dialog ) {

                        }
                    } )
                    .setOnCancelListener( new OnCancelListener() {
                        @Override
                        public void onCancel( DialogInterface dialog ) {

                            boolean coarse = Permission.check( context, permission.ACCESS_COARSE_LOCATION );
                            boolean fine = Permission.check( context, permission.ACCESS_FINE_LOCATION );

                            emitter.onNext( coarse || fine );
                            emitter.onComplete();
                        }
                    } )
                    .create()
                    .show();
            }
        } );
    }

    public static class Dialog extends CancelConfirmDialogFragment {

        private Runnable mRunnable;
        private Runnable mDismiss;

        @Override
        protected android.app.Dialog createDialog( Context context, @Nullable Bundle savedInstanceState ) {

            android.app.Dialog dialog = super.createDialog( context, savedInstanceState );
            mContent.setText( "显示隐私" );

            mCancel.setOnClickListener( new OnClickListener() {
                @Override
                public void onClick( View v ) {

                    dismiss();
                    AMapEasier.notifyUpdatePrivacyAgree( v.getContext(), false );
                }
            } );

            mConfirm.setOnClickListener( new OnClickListener() {
                @Override
                public void onClick( View v ) {

                    dismiss();
                    AMapEasier.notifyUpdatePrivacyAgree( v.getContext(), true );
                    if ( mRunnable != null ) {
                        mRunnable.run();
                    }
                }
            } );

            return dialog;
        }

        public void setRunnable( Runnable runnable ) {

            mRunnable = runnable;
        }

        public void setDismiss( Runnable dismiss ) {

            mDismiss = dismiss;
        }

        @Override
        public void onDismiss( @NonNull DialogInterface dialog ) {

            super.onDismiss( dialog );
            if ( mDismiss != null ) {
                mDismiss.run();
            }
        }

        @Override
        public void onCancel( @NonNull DialogInterface dialog ) {

            super.onCancel( dialog );
            if ( mDismiss != null ) {
                mDismiss.run();
            }
        }
    }
}